/*
 * MCP79410.c
 *
 * Created: 2012-06-02 17:40:33
 *  Author: Sebastian_2
 */ 

#include "MCP79410.h"

#ifndef ATMEGA

// thanks http://picnote.blogspot.com/2009/01/2-digit-bcd-to-decimal-conversion.html
uint8_t bcd2dec(uint8_t bcd) {
	return ((bcd >> 4)*10 + (bcd & 0x0F));
}

uint8_t dec2bcd(uint8_t dec) {
	return ((dec/10) << 4) + (dec%10);
}

void MCP79410_Init() {
	MCP79410_PORT.DIRCLR = MCP79410_INT_bm;
	MCP79410_PORT.PIN2CTRL = PORT_ISC_FALLING_gc | PORT_OPC_PULLUP_gc | PORT_INT1LVL_HI_gc;
	MCP79410_PORT.INT1MASK = MCP79410_INT_bm;
	
	PMIC.CTRL |= PMIC_HILVLEN_bm;
}

void MCP79410_Set(RTCt *rtc) {
	uint8_t buffer[8];
	buffer[0] = 0x80 & dec2bcd(rtc->seconds); // set seconds and start oscillator
	buffer[1] = dec2bcd(rtc->minutes);
	buffer[2] = 0x40 & dec2bcd(rtc->hours); // set hours and select 24h mode
	buffer[3] = 0x08 & dec2bcd(rtc->day); // set day and enable Vbat
	buffer[4] = dec2bcd(rtc->date);
	buffer[5] = dec2bcd(rtc->month);
	buffer[6] = dec2bcd(rtc->year);
	buffer[7] = 0x40; // 1Hz output, no alarms
	
	TWI_MasterWrite(&gTWI_Master, MCP79410_ADDR, &buffer, 8);
}

RTCt MCP79410_Get() {
	RTCt rtc;
	uint8_t buffer[7];
	TWI_MasterWriteRead(&gTWI_Master, MCP79410_ADDR, &buffer, 0, 7);
	rtc.seconds = bcd2dec(0x80 ^ buffer[0]);
	rtc.minutes = bcd2dec(buffer[1]);
	rtc.hours = bcd2dec(0x40 ^ buffer[2]);
	rtc.day = bcd2dec(0x08 ^ buffer[3]);
	rtc.date = bcd2dec(buffer[4]);
	rtc.month = bcd2dec(buffer[5]);
	rtc.year = bcd2dec(buffer[6]);
	
	return rtc;
}

#endif